package com.fastbee.mq.service.impl;

import com.alibaba.fastjson2.JSON;
import com.fastbee.common.core.thingsModel.ThingsModelSimpleItem;
import com.fastbee.iot.domain.*;
import com.fastbee.iot.mapper.*;
import com.fastbee.mq.model.ReportDataBo;
import com.fastbee.mq.service.IFunctionInvoke;
import com.fastbee.mq.service.IRuleEngine;
import com.fastbee.mq.ruleEngine.SceneContext;
import com.yomahub.liteflow.core.FlowExecutor;
import com.yomahub.liteflow.flow.LiteflowResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.List;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;

import static java.util.regex.Pattern.compile;

/**
 * 规则引擎处理数据方法
 *
 * @author bill
 */
@Component
@Slf4j
public class RuleEngineHandler implements IRuleEngine {

    @Resource
    private IFunctionInvoke functionInvoke;
    @Resource
    private SceneDeviceMapper sceneDeviceMapper;

    @Resource
    private FlowExecutor flowExecutor;

    /**
     * 规则匹配(告警和场景联动)
     *
     * @param bo 上报数据模型bo
     * @see ReportDataBo
     */
    public void ruleMatch(ReportDataBo bo) {
        try {
            // 场景联动处理
            this.sceneProcess(bo);
        } catch (Exception e) {
            log.error("接收数据，解析数据时异常 message={}", e, e.getMessage());
        }
    }

    /**
     * 场景规则处理
     */
    public void sceneProcess(ReportDataBo bo) throws ExecutionException, InterruptedException {
        // 查询设备关联的场景
        SceneDevice sceneDeviceParam = new SceneDevice();
        sceneDeviceParam.setProductId(bo.getProductId());
        sceneDeviceParam.setSerialNumber(bo.getSerialNumber());
        List<Scene> sceneList = sceneDeviceMapper.selectTriggerDeviceRelateScenes(sceneDeviceParam);

        int type = bo.getType();
        // 获取上报的物模型
        List<ThingsModelSimpleItem> thingsModelSimpleItems = bo.getDataList();
        if (CollectionUtils.isEmpty(bo.getDataList())) {
            thingsModelSimpleItems = JSON.parseArray(bo.getMessage(), ThingsModelSimpleItem.class);
        }
        // 执行场景规则,异步非阻塞
        for (Scene scene : sceneList) {
            SceneContext context = new SceneContext(bo.getSerialNumber(), bo.getProductId(),type,thingsModelSimpleItems);
            Future<LiteflowResponse> future= flowExecutor.execute2Future(String.valueOf(scene.getChainName()), null, context);
            if (!future.get().isSuccess()) {
                Exception e = future.get().getCause();
                log.error("场景联动执行失败 message={}", e, e.getMessage());
            }
        }
    }

}
